<!--文件-->
<!--chenyi 2019-10-13 11:47:54-->
<template>
  <div>
    <!--搜索条件-->
    <el-form inline :model="searchParam" ref="searchParam" label-width="80px" class="search-form">
      <!--<el-button type="primary" icon="el-icon-upload" @click="upload">上传</el-button>-->
      <es-upload-file action="/admin/file/upload" :data="{parentId:searchParam.parentId}" @uploadSuccess="uploadSuccess"></es-upload-file>

      <el-button type="primary" plain icon="el-icon-folder-add" @click="addFolder">新建文件夹</el-button>
      <el-button-group style="margin-left: 10px;">
        <el-button type="primary" icon="el-icon-download" ref="downloadBtn" :style="'display:'+btnStatus.download+';'">
          下载
        </el-button>
        <el-button type="primary" icon="el-icon-edit" @click="showRename" ref="renameBtn"
                   :style="'display:'+btnStatus.rename+';'">
          重命名
        </el-button>
        <el-button type="primary" @click="showMoveDialog" ref="moveBtn" :style="'display:'+btnStatus.move+';'">移动到
        </el-button>
        <el-button type="primary" icon="el-icon-delete" ref="deleteBtn"
                   @click="handleDelete" :style="'display:'+btnStatus.delete+';'">删除
        </el-button>

      </el-button-group>

      <!--文件选择器-->
      <es-file-selector @select="handleSelectFile"></es-file-selector>

      <div class="file-right-btn">
        <el-input v-model="searchParam.fileNameVague" prefix-icon="el-icon-search" style="width: 250px;"
                  placeholder="搜索您的文件" clearable></el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchForm">查询</el-button>

      </div>

    </el-form>
    <div v-show="catalogArray.length > 1" class="file-catalog" style="width: 100px;">
      <el-breadcrumb separator="|" style="display: inline">
        <el-breadcrumb-item><span @click="returnPrev()" class="a-link">返回上一级</span></el-breadcrumb-item>
        <el-breadcrumb-item></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="file-catalog" style="width: 600px;">
      <el-breadcrumb separator-class="el-icon-arrow-right" style="display: inline">
        <el-breadcrumb-item v-for="(item,index) in catalogArray" :key="item.id">
          <span v-if="index == catalogArray.length-1">{{item.fileName}}</span>
          <span v-else @click="skipFolder(index)" class="a-link">{{item.fileName}}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--表格-->
    <transition name="el-fade-in-linear">
      <div v-show="action === 'list'">
        <el-table
          :data="tableData"
          size="mini"
          v-loading="loading"
          element-loading-text="数据加载中"
          @cell-mouse-enter="cellMouseEnter"
          @cell-mouse-leave="cellMouseLeave"
          @selection-change="handleSelectionChange"
          class="ele-table">

          <el-table-column
            type="selection"
            width="55">
          </el-table-column>

          <el-table-column
            prop="fileType"
            width="55"
          >
            <template slot-scope="scope">
              <img :src="getFileType(scope.row)" style="height:40px">
            </template>
          </el-table-column>

          <el-table-column
            prop="fileName"
            label="文件名"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <template v-if="scope.row.id === editId">
                <el-input
                  style="width: calc(100% - 200px)!important;"
                  placeholder="请输入文件/文件夹名称"
                  v-model="newFileName"
                  clearable>
                </el-input>
                <el-button type="success" icon="el-icon-circle-check"
                           @click="handleRename(scope.$index)">确定
                </el-button>
                <el-button type="warning" icon="el-icon-refresh" @click="editId=0">取消</el-button>
              </template>
              <template v-else>
                <span v-if="scope.row.isFolder == 1 " @click="openFolder(scope.row)" class="file-name">{{scope.row.fileName}}</span>
                <span v-else-if=" scope.row.fileType === 'pic'" class="file-name"
                      @click="fileDetail(scope.row.fileUrl)">{{scope.row.fileName}}</span>
                <span v-else style="cursor: default">{{scope.row.fileName}}</span>
              </template>

            </template>
          </el-table-column>

          <el-table-column
            width="100">
            <template slot-scope="{row}">
              <el-button-group v-show="currentCellId === row.id">
                <el-tooltip class="item" effect="dark" content="打开文件夹" placement="top">
                  <i @click="openFolder(row)" class="el-icon-folder-opened cell-btn" v-if="row.isFolder === 1"></i>
                </el-tooltip>
                <el-dropdown trigger="click" @command="fileCommand">
                                        <span class="el-dropdown-link">
                                           <i class="el-icon-more cell-btn" style="margin-left: 10px;"></i>
                                         </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command='{row:row,command:"download"}'>下载</el-dropdown-item>
                    <el-dropdown-item :command='{row:row,command:"delete"}'>删除</el-dropdown-item>
                    <el-dropdown-item :command='{row:row,command:"rename"}'>重命名</el-dropdown-item>
                    <el-dropdown-item :command='{row:row,command:"move"}'>移动到</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-button-group>
            </template>
          </el-table-column>

          <el-table-column
            prop="fileUrl"
            label="文件地址"
            width="400"
          >
          </el-table-column>
          <el-table-column
            prop="fileSize"
            label="文件大小"
            width="150"
          >
          </el-table-column>

          <el-table-column
            prop="updateTime"
            label="更新时间"
            width="200"
          >
            <template slot-scope="scope">
              <es-time format="yyyy-MM-dd hh:mm:ss" :value="scope.row.updateTime"></es-time>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </transition>
    <!--分页-->
    <el-pagination
      style="margin: 20px;float: right;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-size="searchParam.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog
      :title="'移动到'+(moveTo.fileName||'')"
      :visible.sync="dialogVisible"
      width="500"
    >
      <el-tree ref="folderTree"
               show-checkbox
               check-strictly
               default-expand-all
               :indent="24"
               node-key="value"
               :data="folderData"
               @check-change="handleCheck"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain icon="el-icon-folder-add" @click="treeAddFolder"
                   style="float: left">新建文件夹</el-button>
        <el-button type="primary" @click="handleMoveTo">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
  </span>
    </el-dialog>
    <!--图片预览-->
    <el-dialog :visible.sync="previewImgVisible"  >
      <img :src="dialogImageUrl" style="width: 100%;" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import {getList, remove, selectFolders, addFolder, rename, addToRecycle, moveFile} from '../../api/file/fileApi'
  export default {
    name: 'file',
    data() {
      return {
        searchParam: {//表格数据请求参数
          fileNameVague: '',
          parentId: 0,
          page: 1,
          limit: 10
        },
        title: '',
        action: 'list',
        loading: false,
        item: {},  //修改/详情数据
        multipleSelection: [], //复选框选中的值
        tableData: [],
        total: 0,
        ids: [],
        btnStatus: {
          download: "none",
          delete: "none",
          rename: "none",
          move: "none",
        },
        editId: 0,//行内编辑id
        newFileName: "",//重命名的值
        currentCellId: 0,
        catalogArray: [{id: 0, fileName: "全部文件"}],
        dialogVisible: false,//是否展示下拉文件夹
        previewImgVisible:false,
        dialogImageUrl:"",
        folderData: null,//文件夹目录数据
        moveTo: {
          currentClickId: '',
          fileId: null,
          fileName: null
        }
      }
    },
    mounted() {
      this.getTableData()
    },
    methods: {
      handleSelectFile(checkedList){
        this.$msgbox.alert(checkedList);
      },
      uploadSuccess(res) {
        this.getTableData();
      },
      //文件下拉操作
      fileCommand(obj) {
        switch (obj.command) {
          case 'download':
            break;
          case 'delete':
            let ids = [obj.row.id];
            this.addToRecycle(ids);
            break;
          case 'rename':
            this.newFileName = obj.row.fileName;
            this.editId = obj.row.id;
            break;
          case 'move':
            this.showMoveDialog(obj.row.id);
            break;
          default:

        }
      },
      //返回上一级
      returnPrev() {
        this.skipFolder(this.catalogArray.length - 2);
      },
      //文件夹目录跳转
      skipFolder(index) {
        let catalogArray = this.catalogArray.slice(0, index + 1);
        this.catalogArray = catalogArray;
        this.searchParam.parentId = this.catalogArray[this.catalogArray.length - 1].id;
        //刷新表格数据
        this.getTableData();
      },
      fileDetail(fileUrl) {
        this.previewImgVisible=true;
        this.dialogImageUrl=fileUrl;
      },
      //打开文件夹
      openFolder(parent) {
        this.searchParam.parentId = parent.id;
        //刷新表格数据
        this.getTableData();
        this.catalogArray.push({id: parent.id, fileName: parent.fileName});
      },
      //新增文件夹
      addFolder(parentId,addFromMoveFolder) {
        let _this = this;
        parentId = typeof parentId === 'string' ? parentId : _this.searchParam.parentId;
        _this.$prompt('请输入文件夹名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[\S\s]{1,200}$/,
          inputErrorMessage: '请输入1-200个字符的名称'
        }).then(({value}) => {
          if (!value) {
            _this.$message.error("请输入1-200个字符的名称");
            return false;
          }
          addFolder({parentId: parentId, fileName: value}).then(res => {
            if (res.code === 200) {
              //如果是移动文件夹时添加
              if (addFromMoveFolder) {
                //追加文件夹目录数据
                const newChild = {value: res.newFolderId, label: res.lastName, children: []};
                const checkedNodes = _this.$refs.folderTree.getCheckedNodes();
                if (!checkedNodes[0].children) {
                  this.$set(data, 'children', []);
                }
                checkedNodes[0].children.push(newChild);
              }
              //刷新表格数据
              _this.getTableData();
              _this.$message.success("操作成功!");
            } else {
              _this.$message.error(res.msg);
            }
          });
        })

      },
      showRename() {
        let item = this.multipleSelection;
        this.newFileName = item[0].fileName;
        this.editId = item[0].id;
      },
      //重命名
      handleRename(index) {
        let _this = this;
        let newFileName = this.newFileName;
        let fileId = this.editId;
        rename({fileId: fileId, newFileName: newFileName}).then(res => {
          if (res.code === 200) {
            //刷新表格数据
            _this.$message.success("重命名成功!");
            _this.tableData[index].fileName = newFileName;
            _this.editId = 0;
          } else {
            _this.$message.error(res.msg);
          }
        });
      },
      //批量删除
      handleDelete() {
        //获取选中的id
        let ids = this.getSelectIds();
        if (ids.length > 0) {
          //加入回收站
          this.addToRecycle(ids);
        }
      },
      //加入回收站
      addToRecycle(ids) {
        let _this = this;
        _this.$confirm('确认要把所选文件放入回收站吗？删除的文件可在30天内通过回收站还原', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: function (action, instance) {
            if (action === "confirm") {
              addToRecycle(ids).then(res => {
                if (res.code === 200) {
                  //刷新页面
                  //刷新表格数据
                  _this.getTableData();
                  _this.$message.success("删除成功!");
                  _this.$refs.downloadBtn.$el.style.display = "none";
                  _this.$refs.deleteBtn.$el.style.display = "none";
                  _this.$refs.renameBtn.$el.style.display = "none";
                  _this.$refs.moveBtn.$el.style.display = "none";
                } else {
                  _this.$message.error(res.msg);
                }
              });
            }
          }
        })

      },
      //复选框选择
      handleSelectionChange(val) {
        this.multipleSelection = val;
        if (val.length === 0) {
          this.$refs.downloadBtn.$el.style.display = "none";
          this.$refs.deleteBtn.$el.style.display = "none";
          this.$refs.renameBtn.$el.style.display = "none";
          this.$refs.moveBtn.$el.style.display = "none";
        } else if (val.length === 1) {
          this.$refs.downloadBtn.$el.style.display = "block";
          this.$refs.deleteBtn.$el.style.display = "block";
          this.$refs.renameBtn.$el.style.display = "block";
          this.$refs.moveBtn.$el.style.display = "block";
        } else {
          this.$refs.downloadBtn.$el.style.display = "block";
          this.$refs.deleteBtn.$el.style.display = "block";
          this.$refs.renameBtn.$el.style.display = "none";
          this.$refs.moveBtn.$el.style.display = "none";
        }
      },
      treeAddFolder() {
        let parentId = this.moveTo.fileId;
        if (!parentId) {
          this.$message.error("请先勾选上级文件夹");
          return false;
        }
        this.addFolder(parentId,true);
      },
      handleCheck(data, checked, indeterminate) {
        if (checked === true) {
          this.moveTo.fileId = data.value;
          this.moveTo.fileName = "-" + data.label;
          this.$refs.folderTree.setCheckedKeys([data.value]);
        } else {
          if (this.moveTo.fileId === data.value) {
            this.$refs.folderTree.setCheckedKeys([data.value]);
          }
        }
      },
      //移动文件
      handleMoveTo() {
        let _this = this;
        let params = {fileId: this.moveFileId, parentId: this.moveTo.fileId};
        moveFile(params).then(res => {
          if (res.code === 200) {
            //刷新表格数据
            _this.getTableData();
            _this.$message.success("移动成功!");
            _this.dialogVisible = false;
          } else {
            _this.$message.error(res.msg);
          }
        });

      },
      //显示移动文件弹窗
      showMoveDialog(fileId) {
        if (typeof fileId !== 'string') {
          let chcekeds = this.multipleSelection;
          if (chcekeds.length === 0) {
            this.$message.error("请选择一条数据");
          }
          fileId = chcekeds[0].id;
        }
        let _this = this;
        let params = {fileId: fileId};
        //获取文件夹目录
        selectFolders(params).then(res => {
          if (res.code === 200) {
            _this.folderData = res.data;
            _this.moveFileId = fileId;
            _this.dialogVisible = true;
          } else {
            this.$message.error(res.msg);
          }
        });

      },
      // 复制成功
      onCopy(e) {
        this.$message.success("复制成功");
      },
      // 复制失败
      onError(e) {
        this.$message.error("复制失败");
      },
      cellMouseEnter(row, column, cell, event) {
        this.currentCellId = row.id;
      },
      cellMouseLeave() {
        this.currentCellId = 0;
      },
      getFileType(row) {
        return `/static/img/file/${row.fileType}.png`;
      },
      //获取数据
      getTableData() {
        let _this = this
        _this.loading = true
        getList(_this.searchParam).then((res) => {
          if (res.code === 200) {
            _this.tableData = res.data
            console.log(_this.tableData)
            _this.total = res.total
          } else {
            this.$message.error(res.msg)
          }
          _this.loading = false
        })
      },
      //获取选中行
      getSelectIds(row) {
        let chcekeds = [];
        let ids = [];
        if (!row || Object.keys(row).length === 0) {
          chcekeds = this.multipleSelection;
          if (chcekeds.length === 0) {
            this.$message.error("至少选择一条数据");
          } else {
            for (let key in chcekeds) {
              ids.push(chcekeds[key].id);
            }
          }
        } else {
          ids.push(row.id);
        }
        return ids;

      },
      //查询表格
      searchForm() {
        this.searchParam.page = 1
        //获取数据
        this.getTableData()
      },
      //重置查询表格
      resetSearchForm() {
        this.$refs['searchParam'].resetFields()
        //获取数据
        this.getTableData()
      },
      handleSizeChange(limit) {
        this.searchParam.limit = limit
        //获取数据
        this.getTableData()
      },
      handleCurrentChange(page) {
        this.searchParam.page = page
        //获取数据
        this.getTableData()
      },
    }
  }
</script>

<style scoped>
  .ele-table {
    width: calc(100% - 10px);
    margin-top: 15px;
    padding-right: 10px;
    font-size: 14px !important;
    color: #606266 !important;
  }

  .ele-table .el-button + .el-button {
    margin-left: 0 !important;
  }

  .cell-btn {
    font-size: 20px;
    color: rgb(64, 158, 255);
    cursor: pointer
  }

  .file-right-btn {
    display: inline-block;
    float: right;
    margin-right: 10px;
  }

  .file-name {
    cursor: pointer;
  }

  .file-name:hover {
    color: #409EFF;
  }

  .file-catalog {
    margin-top: 20px;
    display: inline-block;
  }

</style>
